#include <myhead.h>
#include <sqlite3.h>
#include "dao.h"

extern sqlite3* db;

int tbl_group_mygroup(char* username, char* result){
	char sql[]="select distinct groupname from tbl_group where username=?;";
	sqlite3_stmt *pStmt;
	if(sqlite3_prepare_v2(db,sql,sizeof(sql), &pStmt, NULL)!=SQLITE_OK){
		fprintf(stderr, "tbl_friend_mygroup error:%s\n", sqlite3_errmsg(db));
		sqlite3_finalize(pStmt);
		return -1;
	}
	sqlite3_bind_text(pStmt, 1, username, strlen(username), NULL);

	int cnt=0;
	while(sqlite3_step(pStmt)==SQLITE_ROW){
		strcat(result, sqlite3_column_text(pStmt, 0));
		strcat(result, "\n");
		cnt++;
	}

	sqlite3_finalize(pStmt);
	return cnt;
}

int tbl_group_groupmembers(char* groupname, char* res){
	char sql[]="select username from tbl_group where groupname=?;";
	sqlite3_stmt *pStmt;
	if(sqlite3_prepare_v2(db,sql,sizeof(sql), &pStmt, NULL)!=SQLITE_OK){
		fprintf(stderr, "tbl_friend_groupmembers error:%s\n", sqlite3_errmsg(db));
		sqlite3_finalize(pStmt);
		return -1;
	}
	sqlite3_bind_text(pStmt, 1, groupname, strlen(groupname), NULL);

	int cnt=0;
	while(sqlite3_step(pStmt)==SQLITE_ROW){
		strcat(res, sqlite3_column_text(pStmt, 0));
		strcat(res, "\n");
		cnt++;
	}

	sqlite3_finalize(pStmt);
	return cnt;
}

int tbl_group_insert(char* username, char* groupname, char* errmsg){
	char sql[]="insert into tbl_group (username,groupname)values (?,?);";

	sqlite3_stmt *pStmt;
	if(sqlite3_prepare_v2(db,sql,sizeof(sql), &pStmt, NULL)!=SQLITE_OK){
		fprintf(stderr, "tbl_group_insert error:%s\n", sqlite3_errmsg(db));
		sqlite3_finalize(pStmt);
		return -1;
	}
	
	sqlite3_bind_text(pStmt,1, username, strlen(username), NULL);
	sqlite3_bind_text(pStmt,2, groupname, strlen(groupname), NULL);

	int retStep=sqlite3_step(pStmt);
	printf("tbl_group_insert. retStep=[%d]:%s\n", retStep, sqlite3_errmsg(db));
	printf("SQLITE_DONE=%d\n", SQLITE_DONE);
	sqlite3_finalize(pStmt);
	if(retStep == 19){
		strcpy(errmsg, "用户已经在此组");
		return 19;
	}
	if(retStep != SQLITE_DONE)
		return -1;

	return 0;
}

/*
int main(int argc, const char *argv[])
{
	tbl_dao_init();
	
	printf("*******insert测试\n");
	char errmsg[50]={0};
	if(0 != tbl_group_insert("aaa","g2", errmsg)){
		printf("操作失败:%s\n", errmsg);
	}else{
		printf("插入成功\n");
	}
	memset(errmsg, 0 ,50);
	if(0 != tbl_group_insert("bbb","g1", errmsg)){
		printf("操作失败:%s\n", errmsg);
	}else{
		printf("插入成功\n");
	}
	memset(errmsg, 0 ,50);
	if(0 != tbl_group_insert("aaa","g1", errmsg)){
		printf("操作失败:%s\n", errmsg);
	}else{
		printf("插入成功\n");
	}
	
	char res[500]={0};
	int cnt=tbl_group_mygroup("aaa", res);
	printf("查询到[%d]个组:\n%s\n", cnt, res);
	memset(res, 0, 500);
	cnt=tbl_group_mygroup("bbb", res);
	printf("查询到[%d]个组:\n%s\n", cnt, res);

	char res[1000]={0};
	int cnt=tbl_group_groupmembers("g1", res);
	printf("cnt=[%d]\n", cnt);
	printf("%s\n", res);

	char* name=strtok(res, "\n");
	printf("name=[%s]\n", name);
	while(name=strtok(NULL, "\n")){
		printf("name=[%s]\n", name);
	}

	return 0;
}
*/
